//
//  UIImageView+ASIRequest.m
//  HuaWeiApplication
//
//  Created by 02 on 12-4-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//



#define defaultImage @"icon.png"
//#import "MyMethod.h"
#import "UIImageView+ASIRequest.h"

@implementation UIImageView (ASIRequest)
@dynamic helpImage;

- (void)loadImageFromURL:(NSString*)urlString showLoadingImg:(NSString *)img{

    [self setImage:[UIImage imageNamed:img]];
    UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [aiView setFrame:CGRectMake(0, 0, 32, 32)];
    [aiView setCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height/2)];
    [self addSubview:aiView];
    [aiView startAnimating];
    [aiView release];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults]objectForKey:@"cachedImages"];
    
    id path = [dict objectForKey:[url absoluteString]];
    
    if (path && ([[NSFileManager defaultManager]fileExistsAtPath:path] || [[NSBundle mainBundle] pathForResource:path ofType:@"png"])) {
        
        if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            image = [self image:image rotation:image.imageOrientation];
            [self setImage:image];
            
        } else {
            UIImage *image = [UIImage imageNamed:path];
            image = [self image:image rotation:image.imageOrientation];
            [self setImage:image];
        }
        [aiView removeFromSuperview];
        return;
    }
    
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc]init];
    NSDictionary *oldDict = [[NSUserDefaults standardUserDefaults]objectForKey:@"cachedImages"];
    if (oldDict) {
        [muDict addEntriesFromDictionary:oldDict];
    }
    [muDict setObject:img forKey:[url absoluteString]];
    [[NSUserDefaults standardUserDefaults] setObject:muDict forKey:@"cachedImages"];
    [muDict release];

    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *cachesDirectory = [paths objectAtIndex:0];
    
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
    CFRelease(uuid);
    NSString *uniqueFileName = [NSString stringWithFormat:@"%@", (NSString *)uuidString];
    CFRelease(uuidString);
    
    NSString *saveDir = [cachesDirectory stringByAppendingPathComponent:uniqueFileName];
    
//    NSLog(saveDir);
    
    [request setDownloadDestinationPath:saveDir];
    [request setDelegate:[self retain]];
    [request setTimeOutSeconds:25];
    [request setDidFailSelector:@selector(requestImageFailed:)];
    [request setDidFinishSelector:@selector(requestImageSuc:)];
    [request startAsynchronous];

}

- (void)requestImageSuc:(ASIHTTPRequest*)request{
    
    for (id subview in [self subviews]) {
        if ([subview isKindOfClass:[UIActivityIndicatorView class]]) {
            [subview removeFromSuperview];
            break;
        }
    }
   
    if ([[NSFileManager defaultManager]fileExistsAtPath:[request downloadDestinationPath]]) {
        UIImage *image = [UIImage imageWithContentsOfFile:[request downloadDestinationPath]];
        if (image) {
            image = [self image:image rotation:image.imageOrientation];
            [self setImage:image];
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
            NSDictionary *oldDict = [[NSUserDefaults standardUserDefaults]objectForKey:@"cachedImages"];
            if (oldDict) {
                [dict addEntriesFromDictionary:oldDict];
            }
            [dict setObject:[request downloadDestinationPath] forKey:[[request url]absoluteString]];
            [[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"cachedImages"];
            [dict release];
            [self release];
        }else{
        }
    }else{
//        [self requestImageFailed:request];
    }

}
/**
 *  图片宽度大于高度 旋转90°
 *
 *  @param aImage UIImage
 *
 *  @return UIImage
 */

- (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    if (image.size.width > image.size.height) {
        rotate = M_PI_2;
        rect = CGRectMake(0, 0, image.size.height, image.size.width);
        translateX = 0;
        translateY = -rect.size.width;
        scaleY = rect.size.width/rect.size.height;
        scaleX = rect.size.height/rect.size.width;
    }
    else{
        rotate = 0.0;
        rect = CGRectMake(0, 0, image.size.width, image.size.height);
        translateX = 0;
        translateY = 0;
    }
    //    switch (orientation) {
    //        case UIImageOrientationLeft:
    //            rotate = M_PI_2;
    //            rect = CGRectMake(0, 0, image.size.height, image.size.width);
    //            translateX = 0;
    //            translateY = -rect.size.width;
    //            scaleY = rect.size.width/rect.size.height;
    //            scaleX = rect.size.height/rect.size.width;
    //            break;
    //        case UIImageOrientationRight:
    //            rotate = 3 * M_PI_2;
    //            rect = CGRectMake(0, 0, image.size.height, image.size.width);
    //            translateX = -rect.size.height;
    //            translateY = 0;
    //            scaleY = rect.size.width/rect.size.height;
    //            scaleX = rect.size.height/rect.size.width;
    //            break;
    //        case UIImageOrientationDown:
    //            rotate = M_PI;
    //            rect = CGRectMake(0, 0, image.size.width, image.size.height);
    //            translateX = -rect.size.width;
    //            translateY = -rect.size.height;
    //            break;
    //        default:
    //
    //            break;
    //    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize

{
    
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
                                [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
                                UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
                                UIGraphicsEndImageContext();
                                
                                
                                return scaledImage;
                                
    
}

- (void)requestImageFailed:(ASIHTTPRequest*)request{
    for (id subview in [self subviews]) {
        if ([subview isKindOfClass:[UIActivityIndicatorView class]]) {
            [subview removeFromSuperview];
            break;
        }
    }
    
    
//    NSLog(@"fail %i",[self retainCount]);
    
    [self release];
//    [request release];
}


@end
